package com.awspaas.user.apps.processforsap.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListener;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.common.profile.StringUtil;
import com.awspaas.user.apps.processforsap.util.HttpClientGwUtil;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GWTaskValidateForCEI extends InterruptListener implements InterruptListenerInterface {
    @Override
    public boolean execute(ProcessExecutionContext ctx) throws Exception {
        /**
         * 电子
         */
        ProcessInstance processInstance = ctx.getProcessInstance();
        String bindid = processInstance.getId();
        boolean isty = ctx.isChoiceActionMenu("同意");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (isty) {

            List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindid).list();
            String matlGroup = list.get(0).getString("MATL_GROUP");

            //取值
            BO bo11111111 = ctx.getBO("BO_EU_SAP_WLZSJ");


            String matlType2 = list.get(0).getString("MATL_TYPE");


            if (!"Z001/Z002/Z005".contains(matlType2)) {

                //物料特性校验卡控
                BO wltxMainBo = ctx.getBO("BO_EU_SAP_WLTX");
                String watnr = wltxMainBo.getString("MATNR");

                List<BO> listCP = SDK.getBOAPI().query("BO_EU_SAP_CPWLL").bindId(bo11111111.getBindId()).list();
                List<BO> listROH = SDK.getBOAPI().query("BO_EU_SAP_ZCHJCH").bindId(bo11111111.getBindId()).list();
                List<BO> listWAFER = SDK.getBOAPI().query("BO_EU_SAP_WAFER").bindId(bo11111111.getBindId()).list();

                if (watnr.contains("6-GY-00") && matlType2.equals("Z003")) {

                } else {
                    if (listROH != null && listROH.size() > 0) {
                        BO rohBo = listROH.get(0);
                        String zRohMat = rohBo.getString("Z_ROH_MAT");
                        if (StringUtil.equals("X", zRohMat)) {
                            if (StringUtil.isEmpty(rohBo.getString("ZTYPE"))
                                    || StringUtil.isEmpty(rohBo.getString("ZMATNAME"))
                                    || StringUtil.isEmpty(rohBo.getString("ZSPEC"))
                                    || StringUtil.isEmpty(rohBo.getString("ZFIFO"))
                                    || StringUtil.isEmpty(rohBo.getString("ZNONINSP"))
                                    || StringUtil.isEmpty(rohBo.getString("ZMATSTATUS"))
                                    || StringUtil.isEmpty(rohBo.getString("ZCARMATER"))) {
                                throw new BPMNError("0331", "请在ROH（直材或间材）中补齐型号/物料名称/规格/出库优先级/材料状态/免检/汽车材料字段信息!");
                            }
                            if (watnr.contains("1-MC")) {
                                if (StringUtil.isEmpty(rohBo.getString("ZMATNAME"))) {
                                    throw new BPMNError("0331", "当物料类型为1-MC时，请在ROH（直材或间材）中补齐是否高导热材料字段信息!");
                                }
                            }
                            if (watnr.contains("1-CP") || watnr.contains("1-ID") || watnr.contains("1-RS")) {
                                if (StringUtil.isEmpty(rohBo.getString("ZCOMPTYPE")) || StringUtil.isEmpty(rohBo.getString("ZSIZE"))) {
                                    throw new BPMNError("0331", "当物料类型为1-CP/1-ID/1-RS时，请在ROH（直材或间材）中补齐元器件尺寸/元器件类型字段信息!");
                                }
                            }
                            if (watnr.contains("1-SB")) {
                                if (StringUtil.isEmpty(rohBo.getString("ZHAVECU"))
                                        || StringUtil.isEmpty(rohBo.getString("ZLAYER"))
                                        || StringUtil.isEmpty(rohBo.getString("ZCORE"))
                                        || StringUtil.isEmpty(rohBo.getString("ZSUBTYPE"))) {
                                    throw new BPMNError("0331", "当物料类型为1-SB时，请在ROH（直材或间材）中补齐基板类型/基板层数/基板是否含铜/有无core材字段信息!");
                                }
                            }
                        }
                    }
                }
            }


            //获取物料特性
            BO bo1 = SDK.getBOAPI().query("BO_EU_SAP_CPWLL").detailByBindId(bindid);
            BO bo2 = SDK.getBOAPI().query("BO_EU_SAP_ZCHJCH").detailByBindId(bindid);
            BO bo3 = SDK.getBOAPI().query("BO_EU_SAP_WAFER").detailByBindId(bindid);
            String specifiCations = "";
            String zgyunit = "";
            String copGName = "";
            if (bo1 != null) {
                if (StringUtil.isNotEmpty(bo1.getString("ZSPEC"))) {
                    specifiCations = bo1.getString("ZSPEC");
                }
                if (StringUtil.isNotEmpty(bo1.getString("ZGYUNIT"))) {
                    zgyunit = bo1.getString("ZGYUNIT");
                }
                if (StringUtil.isNotEmpty(bo1.getString("ZMATNAME"))) {
                    copGName = bo1.getString("ZMATNAME");
                }
            }
            if (bo2 != null) {

                String zcmatnr = bo2.getString("ZCMATNR");
                String zcustomcode = bo2.getString("ZCUSTOMER");
                String zsize = bo2.getString("ZSIZE");
                String zcomptype = bo2.getString("ZCOMPTYPE");
                String zgg = bo2.getString("ZGG");
                String zcarmater = bo2.getString("ZCARMATER");
                String zspec = bo2.getString("ZSPEC");


                if (StringUtil.isNotEmpty(bo2.getString("ZSPEC"))) {
                    specifiCations = bo2.getString("ZSPEC");
                }
                if (StringUtil.isNotEmpty(bo2.getString("ZGYUNIT"))) {
                    zgyunit = bo2.getString("ZGYUNIT");
                }
                if (StringUtil.isNotEmpty(bo2.getString("ZMATNAME"))) {
                    copGName = bo2.getString("ZMATNAME");
                }

                if ("RDK/RDT/RDZ/RDN/RDX/RDQ/KDR/RTL/RDA/SAD/GAX".contains(zcustomcode)) {
                    if (StringUtils.isEmpty(zcmatnr)) {
                        throw new BPMNError("0331", "当客户三码为RDK/RDT/RDZ/RDN/RDX/RDQ/KDR/RTL/RDA/SAD/GAX时，客户材料代码必填!");
                    }
                }
                if (matlGroup.startsWith("1-SB") || matlGroup.startsWith("1-IC")) {

                } else {
                    if (StringUtil.isNotEmpty(zspec) && StringUtil.isNotEmpty(zcarmater)) {

                    } else {
                        if (StringUtils.isEmpty(zsize) || StringUtils.isEmpty(zcomptype) || StringUtils.isEmpty(zcarmater)) {
                            throw new BPMNError("0331", "元器件类型、元器件尺寸、汽车材料必填!");
                        }
                    }
                }

                //20250306,与周雪琼老师沟通去掉此卡控
//                if (!zgg.contains("±")) {
//                    throw new BPMNError("0331", "规格中必须包含±符号!");
//                }
                String result = getFirstNumber(zgg);
                if (StringUtils.isNotEmpty(result)) {
                    //先转数值
                    String result1[] = result.split("\\.");
                    if (result1.length == 1) {
                        int d = Integer.valueOf(result);
                        if (d < 10) {
                            throw new BPMNError("0331", "在元器件规格值<10时需要保留一位小数!");
                        }
                    } else if (result1.length == 2) {
                        String xs = result1[1];
                        if (xs.length() > 1) {
                            throw new BPMNError("0331", "仅能保留一位小数!");
                        }
                    }

                }


            }
            if (bo3 != null) {
                if (StringUtil.isNotEmpty(bo3.getString("ZSPEC"))) {
                    specifiCations = bo3.getString("ZSPEC");
                }
                if (StringUtil.isNotEmpty(bo3.getString("ZGYUNIT"))) {
                    zgyunit = bo3.getString("ZGYUNIT");
                }
                if (StringUtil.isNotEmpty(bo3.getString("ZMATNAME"))) {
                    copGName = bo3.getString("ZMATNAME");
                }

                String zwafersize = bo3.getString("ZWAFERSIZE");
                String zWaferMat = bo3.getString("Z_WAFER_MAT");
                String zcustomcode = bo3.getString("ZCUSTOMCODE");
                String znotch = bo3.getString("ZNOTCH");
                String zcmatnr = bo3.getString("ZCMATNR");
                String zgaas = bo3.getString("ZGAAS");


                if (zWaferMat.equals("X")) {
                    if (StringUtils.isEmpty(zwafersize)) {
                        throw new BPMNError("0331", "Wafersize必填!");
                    }
                    if (zwafersize.equals("8")) {
                        if (StringUtils.isEmpty(znotch)) {
                            throw new BPMNError("0331", "当Wafersize为8寸时，Notch类型必填!");
                        }
                    }
                }
                if ("RDK/RDT/RDZ/RDN/RDX/RDQ/KDR/RTL/RDA/SAD/GAX".contains(zcustomcode)) {
                    if (StringUtils.isEmpty(zcmatnr)) {
                        throw new BPMNError("0331", "当客户三码为RDK/RDT/RDZ/RDN/RDX/RDQ/KDR/RTL/RDA/SAD/GAX时，客户材料代码必填!");
                    }
                }
                if ("BVE/SVE".contains(zcustomcode) && matlGroup.startsWith("1-WF")) {
                    if (StringUtils.isEmpty(zgaas)) {
                        throw new BPMNError("0331", "当客户三码为BVE/SVE并且物料组为1-WF时，是否GaAs晶圆必填!");
                    }
                }
            }

            //存储视图校验
            List<BO> ccList = SDK.getBOAPI().query("BO_EU_SAP_CCST").bindId(bindid).list();
            for (BO bo111 : ccList) {
                int shelfLife = Integer.valueOf(StringUtil.isEmpty(bo111.getString("SHELF_LIFE")) ? "0" : bo111.getString("SHELF_LIFE"));
                if (shelfLife <= 0) {
                    throw new BPMNError("0331", "存储视图总货架寿命必填，请核查！");
                }
            }
            //MRP视图校验
            List<BO> mrpList = SDK.getBOAPI().query("BO_EU_SAP_MRP").addQuery("MRP_VIEW='X'", null).bindId(bindid).list();
            for (BO bo : mrpList) {
                String roundVal = bo.getString("ROUND_VAL");
                if ("ROH".equals(matlType2)) {
                    if (matlGroup.startsWith("1-WF") || matlGroup.startsWith("1-IC")) {

                    } else if (StringUtil.isEmpty(roundVal)) {
                        throw new BPMNError("0331", "MRP视图舍入值必填！");
                    }
                }
            }
        }
        return true;
    }

    public static String getFirstNumber(String input) {
        // 使用正则表达式匹配第一个数字
        // 正则表达式
        String regex = "[-+]?\\d+(\\.\\d*)?|[-+]?\\.\\d+";

        // 编译正则
        Pattern pattern = Pattern.compile(regex);

        // 创建Matcher对象
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            return matcher.group();  // 返回找到的第一个数字
        } else {
            return null;  // 如果没有找到数字，返回null
        }
    }

    public static int getDecimalPlaces(double number) {
        // 将数字转换为字符串
        String numberStr = String.valueOf(number);

        // 判断小数点的位置
        int decimalIndex = numberStr.indexOf(".");

        if (decimalIndex == -1) {
            return 0;  // 如果没有小数点，返回0
        } else {
            // 返回小数点后面的位数
            return numberStr.length() - decimalIndex - 1;
        }
    }
}
